package LeetCode.interview;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

import LeetCode.interview._101_Symmetric_Tree.TreeNode;
import LeetCode.interview._141_Linked_List_Cycle.ListNode;
import sun.tools.jar.resources.jar;
import util.ChangeUtils;
import util.LogUtils;

/*
 * 
原题

	　Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.
	
	The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
	
	You may assume that each input would have exactly one solution.
	
	Input: numbers={2, 7, 11, 15}, target=9
	Output: index1=1, index2=2

题目大意
	给定一个有序数组 和 一个给定的数，在数组中找两个数的下标，使这两个数的和等于给定的数
	注：题目已经声明一定有解
解题思路

 * @Date 2017-09-25 23：20
 */
public class _167_Two_Sum_II__Input_array_is_sorted {
	/**
	 * 因为是有序数组、所以二分法
	 */
    /** initialize your data structure here. */
    public int[] twoSum(int[] numbers, int target) {
    	int n = numbers.length;
    	//二分,分别从头尾遍历
    	int l = 0, r = n-1;
    	List<Integer> rs = new ArrayList<Integer>();
    	if (numbers.length < 2) {
    		return ChangeUtils.changeToArr(rs);
    	}
    	while (l < r) {
    		int sum = numbers[l] + numbers[r];
    		if (sum > target) {
    			r--;
    		} else if (sum < target) {
    			l++;
    		} else {
    			//找到
    			rs.add(l+1);
    			rs.add(r+1);
    			break;
    		}
    	}
    	traverse(rs);
    	return ChangeUtils.changeToArr(rs);
    }
    
    

    public void traverse(List<Integer> list) {
    	for (int i : list) {
    		LogUtils.print(i);
    	}
    }


	public static void main(String[] args) {
		_167_Two_Sum_II__Input_array_is_sorted obj = new _167_Two_Sum_II__Input_array_is_sorted();
		obj.twoSum(new int[]{2, 3, 4}, 6);
	}

}
